package com.tianji.promotion.task;

import com.baomidou.mybatisplus.extension.plugins.pagination.PageDto;
import com.tianji.common.utils.CollUtils;
import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.enums.CouponStatus;
import com.tianji.promotion.service.ICouponService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
@RequiredArgsConstructor
public class ListenSendCoupon {
    private final ICouponService couponService;

    //@Scheduled( cron = "0 0 5 * * ?")//每天早上五点执行
    @XxlJob("ListenSendCouponToAll")
    public void ListenSendCouponToAll(){
        int index = XxlJobHelper.getShardIndex();
        int size = XxlJobHelper.getShardTotal();
        int PageSize=10;//每页大小
        int PageNo=1+index;//当前页码
        //查询出所有未发放的优惠卷，并且开始时间小于等于当前时间
        log.info("定时派送优惠卷开始了，{}",LocalDateTime.now());
       while(true){
           PageDto<Coupon> page = couponService.lambdaQuery()
                   .eq(Coupon::getStatus, CouponStatus.DRAFT)
                   .le(Coupon::getIssueBeginTime, LocalDateTime.now()).page(new PageDto<>(PageNo, PageSize));
           List<Coupon> records = page.getRecords();
           if (CollUtils.isEmpty(records)){
               log.info("没有需要派送的优惠卷了");
               break;
           }
           ArrayList<Coupon> list = new ArrayList<>(PageSize);
           for (Coupon coupon : records) {
              coupon.setStatus(CouponStatus.ISSUING);
              list.add(coupon);
           }
           couponService.updateBatchById(list);
           PageNo+=size;
       }
    }
}
